<?php
	define('FORGOT_PWD_SERVICE',true);
	require_once 'ForgotPwdService.class.php';	

	require_once '../Classes/User.class.php';
	require_once '../Tool/Common/PasswordHash.php';
	require_once '../Tool/Common/PrepareInput.php';

	session_start();

	//Generate random string with 10 length
	function generateRandomString($length = 8) {
		$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$randomString = '';
		for ($i = 0; $i < $length; $i++) {
			$randomString .= $characters[rand(0, strlen($characters) - 1)];
		}
		return $randomString;
	}
	
	//Create a ForgotPwdService class
	$forgotPwdService = new ForgotPwdService();
	
	//Resend token key 
	if(!empty($_POST['hashValue'])){
		$flag=0;

		$hashValue=$_POST['hashValue'];

		if(empty($_SESSION[$hashValue])){
			$flag=1;
			echo $flag;		
			exit();
		}else{
			$receiverAddress=$_SESSION[$hashValue];	
		}

		//Generate new random token key
		$tokenKey=generateRandomString();
		
		//Hash token key
		$salt = uniqid('SALT');
		$hashValue=sha1($tokenKey.$salt);

		//Set expired time (1hr)
		$expireTime=date('Y/m/d H:i:s',strtotime('+1 hour'));

		//Set expired value 
		$expired="0";

		//Insert token into database
		$res=$forgotPwdService->insertTokenKey($tokenKey,$expireTime,$expired,$hashValue);
		
		
		if($res === true){
			//Send token email
			$emailRes=$forgotPwdService->sendTokenKey($receiverAddress,$tokenKey,$hashValue,$expireTime);
			
			//Determine send email result
			if($emailRes){
				//Success	
				//Store User Email
				$_SESSION[$tokenKey]=$receiverAddress;	
				$_SESSION[$hashValue]=$receiverAddress;	
				$flag=2;
			}
		}
		echo $flag;		
	}else{
		//Create new token key 
		//Create a User class
		$user = new User();
		
		//Reset Pwd by username
		if(!empty($_POST['username'])){
			//retrieve usernanme
			$username=prepareInput($_POST['username']);
			if (!preg_match("/^[0-9A-Za-z ]*$/",$username)){
				header('Location: ../ResetPwd.php?msgno=6');
				exit();
			}
			$user=$forgotPwdService->retrieveUserByUserName($username);
			if(!empty($user)){		
				//Retrieve user email address
				$receiverAddress=$user->getEmail();
				
				//Generate random token key
				$tokenKey=generateRandomString();
				
				//Hash token key
				$salt = uniqid('SALT');
				$hashValue=sha1($tokenKey.$salt);

				//Set expired time (1hr)
				$expireTime=date('Y/m/d H:i:s',strtotime('+1 hour'));

				//Set expired value 
				$expired="0";

				//Insert token into database
				$res=$forgotPwdService->insertTokenKey($tokenKey,$expireTime,$expired,$hashValue);
				
				if($res === true){
					//Send token email
					$emailRes=$forgotPwdService->sendTokenKey($receiverAddress,$tokenKey,$hashValue,$expireTime);
				
					//Determine send email result
					if($emailRes){
						//Success	
						//Store User Email
						$_SESSION[$tokenKey]=$receiverAddress;	
						$_SESSION[$hashValue]=$receiverAddress;	

						header('Location: ../ResetPwd.php?msgno=1');
						exit();
					}//Fail
					else{
						header('Location: ../ResetPwd.php?msgno=4');
						exit();
					}
				}else{
					header('Location: ../ResetPwd.php?msgno=5');
					exit();
				}			
			}else{
				//No user exists
				header('Location: ../ResetPwd.php?msgno=2');
				exit();
			}	
		}
		//Reset Pwd by email
		else if(!empty($_POST['email'])){
			//retrieve user email address
			$receiverAddress=prepareInput($_POST['email']);
			if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$receiverAddress)){
				header('Location: ../ResetPwd.php?msgno=7');
				exit();
			}
			$user=$forgotPwdService->retrieveUserByEmail($receiverAddress);
			if(!empty($user)){	
				//Generate random token key
				$tokenKey=generateRandomString();
				
				//Hash token key
				$salt = uniqid('SALT');
				$hashValue=sha1($tokenKey.$salt);

				//Set expired time (1hr)
				$expireTime=date('Y/m/d H:i:s',strtotime('+1 hour'));

				//Set expired value 
				$expired="0";

				//Insert token into database
				$res=$forgotPwdService->insertTokenKey($tokenKey,$expireTime,$expired,$hashValue);
				
				if($res === true){
					//Send token email
					$emailRes=$forgotPwdService->sendTokenKey($receiverAddress,$tokenKey,$hashValue,$expireTime);
				
					//Determine send email result
					if($emailRes){
						//Success
						//Store User Email
						$_SESSION[$tokenKey]=$receiverAddress;	
						$_SESSION[$hashValue]=$receiverAddress;	

						header('Location: ../ResetPwd.php?msgno=1');
						exit();
					}//Fail
					else{
						header('Location: ../ResetPwd.php?msgno=4');
						exit();
					}
				}else{
					header('Location: ../ResetPwd.php?msgno=5');
					exit();
				}			
			}else{
				//No user exists
				header('Location: ../ResetPwd.php?msgno=3');
				exit();
			}	
		}
	}
?>